package ai.leinao.notify.email;

import ai.leinao.notify.core.NotifyProperties;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * email 配置
 * 方便获取邮件配置
 * @author zhong.wang
 * @date 2025/7/9
 */
@Getter
@Setter
public class EmailProperties {
    /**
     * 邮件服务器
     */
    private String host;

    /**
     * 端口
     */
    private int port;

    /**
     * 是否使用SSL
     */
    private boolean ssl;

    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * 发送者
     */
    private String sender;

    /**
     * 协议
     */
    private String protocol;

    /**
     * 配置
     */
    private List<ConfigProperty> properties;

    @Getter
    @Setter
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ConfigProperty {
        /**
         * 属性名
         */
        private String name;

        /**
         * 属性值
         */
        private String value;

        /**
         * 描述
         */
        private String description;
    }

    /**
     * 创建JavaMailProperties
     * @return
     */
    public Properties convertProperties() {
        Properties properties = new Properties();
        if (this.properties != null) {
            for (ConfigProperty property : this.properties) {
                properties.put(property.getName(), property.getValue());
            }
        }
        if(ssl){
            properties.putIfAbsent("mail.smtp.auth","true");
            properties.putIfAbsent("mail.smtp.ssl.enable","true");
        }
        return properties;
    }

    /**
     * 配置转换
     * @param properties
     * @return
     */
    public static EmailProperties of(NotifyProperties properties){
        EmailProperties emailProperties = new EmailProperties();
        emailProperties.setHost(properties.getConfiguration().remove("host").toString());
        emailProperties.setPort(Integer.parseInt(properties.getConfiguration().remove("port").toString()));
        emailProperties.setSsl(Boolean.parseBoolean(properties.getConfiguration().remove("ssl").toString()));
        emailProperties.setUsername(properties.getConfiguration().remove("username").toString());
        emailProperties.setPassword(properties.getConfiguration().remove("password").toString());
        emailProperties.setSender(properties.getConfiguration().remove("sender").toString());
        emailProperties.setProtocol(properties.getConfiguration().remove("protocol").toString());
        emailProperties.setProperties(properties.getConfiguration().entrySet().stream().map(entry -> new EmailProperties.ConfigProperty(entry.getKey(), entry.getValue().toString(), "")).collect(Collectors.toList()));
        return emailProperties;
    }
}
